package com.rainman.simpleredis.core.distributed_lock;

import com.rainman.simpleredis.core.config.SimpleRedisConfig;

import java.time.Duration;

/**
 * 分布式悲观锁
 *
 */
public class SimpleDistributedLock {
    private final SimpleRedisConfig simpleRedisConfig;

    private final String DLockHead;//RS0.DLock.

    public SimpleDistributedLock(SimpleRedisConfig simpleRedisConfig ){

        this.simpleRedisConfig = simpleRedisConfig;

        DLockHead=simpleRedisConfig.getKeyHead()+simpleRedisConfig.getProduct()
                +"."+simpleRedisConfig.getDistributedLockHead()+".";//RS0.DLock.
    }

    /**
     * 加锁
     *
     * @param key 键，最终入库会加上头 RS0.DLock.加上这个参数key
     * @param dur 过期毫秒数
     * @return 是否上锁成功
     */
    public Boolean dLockAdd(String key,Long dur){

        Boolean suc = simpleRedisConfig.getRedisInterface().setIfAbsent(
                DLockHead+key
                , "", Duration.ofMillis(dur));

        return suc;
    }


    /**
     * 删除锁
     *
     * @param key 最终会删除 加上头 RS0.DLock.加上这个参数key
     */
    public Boolean dLockRemove(String key){

        Boolean delete = simpleRedisConfig.getRedisInterface().delete(DLockHead + key);

        return delete;
    }


    /**
     * 是否有锁
     *
     * @param key 最终会查询 加上头 RS0.DLock.加上这个参数key
     * @return
     */
    public Boolean hasLock(String key){

        Boolean aBoolean = simpleRedisConfig.getRedisInterface().hasKey(DLockHead + key);

        return aBoolean;
    }

    /**
     * 是否有锁模糊匹配
     *
     * @param keys 最终会查询 加上头 RS0.DLock.加上这个参数key
     * @return
     */
    public Boolean hasLockMatch(String keys){


        int size = simpleRedisConfig.getRedisInterface().keys(DLockHead + keys + ":*").size();

        return size>0;
    }


}
